package com.example.homework.controller;


import com.example.homework.domain.Movie;
import com.example.homework.repository.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "movie")
public class MovieController {
    @Autowired
    private MovieRepository movieRepository;

    //跳转到index页面
    @GetMapping(value = "/index")
    public String index(Model model){
        List<Movie> list = movieRepository.findAll();
        model.addAttribute("list",list);
        return "movie/index";
    }

    //跳转到add页面
    @GetMapping(value = "/add")
    public String toAdd(){
        return "movie/add";
    }

    //添加电影
    @PostMapping(value = "/add")
    public String doAdd(@RequestParam String name, @RequestParam String photo, @RequestParam String createDate){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(createDate);
        } catch (Exception e) {
        }


        System.out.println("name = " + name);
        Movie movie = new Movie();
        movie.setName(name);
        movie.setPhoto(photo);
        movie.setCreateDate(date);
        movieRepository.save(movie);

        //重定向到index.html页面
        //有两种方式：重定向（浏览器），请求转发（服务器）
        return "redirect:/movie/index";
    }

    //删除电影后重定向到index页面
    @GetMapping(value = "/delete/{movieId}")
    public String delete(@PathVariable Long movieId){
        movieRepository.delete(movieId);
        return "redirect:/movie/index";
    }

    //电影详细界面
    @GetMapping(value = "/detail/{movieId}")
    public String toDetail(Model model,@PathVariable Long movieId){

        Movie movie = movieRepository.findOne(movieId);
        model.addAttribute("info",movie);

        return "movie/detail";
    }

    //跳转到编辑界面
    @GetMapping(value = "edit/{movieId}")
    public String toEdit(Model model,@PathVariable Long movieId){
        Movie movie = movieRepository.findOne(movieId);

        model.addAttribute("info",movie);
        return "movie/edit";
    }

    @PostMapping(value = "/edit")
    public String doEdit(@RequestParam String name, @RequestParam String photo, @RequestParam String createDate,@RequestParam Long id){

        Movie movie = movieRepository.findOne(id);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(createDate);
        } catch (Exception e) {
        }
        movie.setCreateDate(date);
        movie.setName(name);
        movie.setPhoto(photo);
        movieRepository.save(movie);

        return "redirect:/movie/index";
    }

}
